package com.hmdp.interceptor;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;

/**
 * 这个拦截器是用来检查网络是否连接的功能
 */
public class NetInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查网络是否连接，如果连接则放行，如果没连接网络，弹出提示窗：请链接网络后访问
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","text/json;charset=UTF-8");
        URL url = null;
        try {
            url = new URL("http://taobao.com/");
            url.openStream();//打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
//            System.out.println("连接成功꒰ঌ( ⌯' '⌯)໒꒱");
        } catch (IOException e) {
            //拦截
//            System.out.println("连接失败(-̩̩̩-̩̩̩-̩̩̩-̩̩̩-̩̩̩___-̩̩̩-̩̩̩-̩̩̩-̩̩̩-̩̩̩)");
//            response.setHeader("errmsg","PLEASE CHECK YOUR NET");
//            response.setHeader("errmsg","请检查网络");
            response.getWriter().write(JSONUtil.toJsonStr(new Result(false,"请检查网络(-̩̩̩-̩̩̩-̩̩̩-̩̩̩-̩̩̩___-̩̩̩-̩̩̩-̩̩̩-̩̩̩-̩̩̩)",null,null)));
            return false;
        }
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
